import CryptoJS from "crypto-js";
import {JSEncrypt} from "jsencrypt";

const PUBLIC_KEY = import.meta.env.VITE_PUBLIC_KEY
export class ApiEncrypt {

    //生成Aes秘钥
    static getAesKey() {
       return CryptoJS.lib.WordArray.random(16).toString();
    }

    //加密随机秘钥
    static getSecret(aesKey) {
        const encryptor = new JSEncrypt();
        encryptor.setPublicKey(PUBLIC_KEY);
        return encryptor.encrypt(aesKey);
    }

    //请求加密
    static encrypt(aesKey, value) {
        if (!value) {
            return '';
        }
        value = JSON.stringify(value)
        const key = CryptoJS.enc.Utf8.parse(aesKey)
        let encrypt = CryptoJS.AES.encrypt(value.toString(), key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return (encrypt.toString() + '').replace(/\n*$/g, '').replace(/\n/g, '');
    }

    //响应解密
    static decrypt(value) {
        if (!value) {
            return '';
        }
        try {
            const vals = (value + '').replace(/\n*$/g, '').replace(/\n/g, '')
            const options = {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            };
            const key = PUBLIC_KEY.substring(0,32)
            const newKey = CryptoJS.enc.Utf8.parse(key);
            const decryptedData = CryptoJS.AES.decrypt(vals, newKey, options);
            return CryptoJS.enc.Utf8.stringify(decryptedData).toString();
        } catch (e) {
            console.error(e);
        }
    }
}